﻿//   DiagnosticsService.cs
//   Copyright (c) 2012 Eswar Prakash
// 
//    This library is free software; you can redistribute it and/or modify  
//    it  under the terms of the GNU Lesser General Public License version  
//    2.1 as published by the Free Software Foundation.                     
//                                                                          
//    This library is distributed in the hope that it will be useful, but   
//    WITHOUT ANY WARRANTY; without even the implied warranty of            
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     
//    Lesser General Public License for more details.                       
//                                                                          
//    You should have received a copy of the GNU Lesser General Public      
//    License along with this library; if not, write to the Free Software   
//    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
//    USA                                                                 
// 

namespace CKSAS.Core.Diagnostics
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint.Administration;
    using System.Reflection;
    using Utilities;

    /// <summary>
    /// Represents the diagnostics service which will be used to write ULS log entries
    /// </summary>
    internal sealed class DiagnosticsService : SPDiagnosticsServiceBase
    {
        /// <summary>
        /// Private member to hold a cache of categories and areas
        /// </summary>
        private static List<DiagnosticItem> itemCache = null;

        /// <summary>
        /// Private member to hold the unique name of the diag service in the farm
        /// </summary>
        private const string DIAG_SERVICE_NAME = "CKSCoreDiagnosticService";

        /// <summary>
        /// Initializes a new instance of the <see cref="DiagnosticsService"/> class.
        /// </summary>
        public DiagnosticsService()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DiagnosticsService"/> class.
        /// </summary>
        /// <param name="name">The name of the service in the farm</param>
        /// <param name="parent">The parent farm that will host this service</param>
        public DiagnosticsService(string name, SPFarm parent)
            : base(name, parent)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DiagnosticsService"/> class.
        /// </summary>
        /// <param name="parent">The parent farm where this service is deployed.</param>
        public DiagnosticsService(SPFarm parent)
            : base(DIAG_SERVICE_NAME, parent)
        {
        }

        /// <summary>
        /// Provides diagnostic areas for logging trace and event entries into the SharePoint
        /// ULS logs
        /// </summary>
        /// <returns></returns>
        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            return this.CreateAreasFromEnum();
        }

        /// <summary>
        /// Creates diagnostic area objects from the diagnostic area and category enumerations
        /// </summary>
        /// <returns></returns>
        private List<SPDiagnosticsArea> CreateAreasFromEnum()
        {
            if (itemCache == null)
            {
                itemCache = new List<DiagnosticItem>();

                var enumFields = typeof (DiagnosticCategories)
                    .GetFields()
                    .Where(x => !x.IsSpecialName);
                foreach (var field in enumFields)
                {
                    // what is the title associated with the field
                    string fieldTitle = String.Empty;
                    var attrib = field.GetCustomAttributes(false)
                        .OfType<DiagnosticTitleAttribute>()
                        .FirstOrDefault();
                    if (attrib != null)
                    {
                        fieldTitle = attrib.Title;
                    }
                    else
                    {
                        fieldTitle = field.Name.AsTitle();
                    }

                    DiagnosticsAreas parentArea = DiagnosticsAreas.CKSAS;

                    var areaAttrib = field.GetCustomAttributes(false)
                        .OfType<DiagnosticAreaAttribute>()
                        .FirstOrDefault();
                    if (areaAttrib != null)
                    {
                        parentArea = areaAttrib.ParentArea;
                    }

                    itemCache.Add(new DiagnosticItem()
                                      {
                                          Category =
                                              (DiagnosticCategories)
                                              Enum.Parse(typeof (DiagnosticCategories), field.Name),
                                          Title = fieldTitle,
                                          ParentArea = parentArea
                                      });
                }
            }

            // create the diagnostic area
            List<SPDiagnosticsArea> diagAreaList = new List<SPDiagnosticsArea>();

            var areaFields = typeof (DiagnosticsAreas)
                .GetFields()
                .Where(x => !x.IsSpecialName);
            foreach (var field in areaFields)
            {
                // what is the title associated with the field
                string fieldTitle = String.Empty;
                var attrib = field.GetCustomAttributes(false)
                    .OfType<DiagnosticTitleAttribute>()
                    .FirstOrDefault();
                if (attrib != null)
                {
                    fieldTitle = attrib.Title;
                }
                else
                {
                    fieldTitle = field.Name.AsTitle();
                }

                var diagArea = (DiagnosticsAreas) Enum.Parse(typeof (DiagnosticsAreas), field.Name);

                diagAreaList.Add(new SPDiagnosticsArea(fieldTitle, itemCache
                                                                       .Where(x => x.ParentArea == diagArea)
                                                                       .Select(
                                                                           x =>
                                                                           new SPDiagnosticsCategory(x.Title,
                                                                                                     TraceSeverity.
                                                                                                         Medium,
                                                                                                     EventSeverity.Error))
                                                                       .ToList()));
            }

            return diagAreaList;
        }

        /// <summary>
        /// Registers the diagnostic service in the given farm
        /// </summary>
        /// <param name="parentFarm">The parent farm where the diagnostics service should be registered.</param>
        internal static void RegisterService(SPFarm parentFarm)
        {
            var localService = SPDiagnosticsServiceBase.GetLocalToFarm<DiagnosticsService>(parentFarm);
            if (localService == null)
            {
                localService = new DiagnosticsService(parentFarm);
                localService.Update();
            }
        }

        /// <summary>
        /// Unregisters the diagnostic service from the given farm
        /// </summary>
        /// <param name="parentFarm">The parent farm from where the service should be unregistered.</param>
        internal static void UnregisterService(SPFarm parentFarm)
        {
            var localService = SPDiagnosticsServiceBase.GetLocalToFarm<DiagnosticsService>(parentFarm);
            if (localService != null)
            {
                localService.Delete();
            }
        }

        /// <summary>
        /// Gets the local instance of the diagnostics service
        /// </summary>
        internal static DiagnosticsService Local
        {
            get { return GetLocalToFarm<DiagnosticsService>(SPFarm.Local); }
        }

        /// <summary>
        /// Represents an internal private class used to cache diagnostic area and category information
        /// </summary>
        private class DiagnosticItem
        {
            /// <summary>
            /// Gets or sets the parent area.
            /// </summary>
            public DiagnosticsAreas ParentArea { get; set; }

            /// <summary>
            /// Gets or sets the category enumeration associated with this
            /// item
            /// </summary>
            public DiagnosticCategories Category { get; set; }

            /// <summary>
            /// Gets or sets the expanded name of the category.
            /// </summary>
            public string Title { get; set; }
        }
    }
}